<!--
* @FileDescription: 模版配置页面组件
* @Author: yuec621@outlook.com
* @Date: 2024-09-10 13:56:18
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-06-06 16:00:22
-->
<template>
    <div>
        <el-form ref="formRef" :model="state.formData" :rules="state.rules"
         v-if="mobanType == 'C'">
            <el-row :gutter="20" style="margin-top:10px;" v-if="tabradio=='detail'">
                <el-col :span="24">
                    <div class="fss">
                        <el-form-item label="模板类型" prop="templateType">
                            <el-select v-model="state.formData.templateType" style="margin-right: 10px;">
                                <el-option v-for="item in ['分站模板']" :key="item" :label="item" :value="item" />
                            </el-select>
                        </el-form-item>
                        <slot name="formtemDatatype"></slot>
                        <el-form-item label="模板名称" prop="templateName">
                            <el-input v-model="state.formData.templateName" placeholder="请输入"></el-input>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="24">
                    <vxe-table border="inner" height="500" show-overflow ref="tableRef" :data="state.formData.nodeList">
                        <vxe-column field="code" title="测点号">
                            <template #default="{ row }">
                                <el-select v-model="row.code" v-if="row.show">
                                    <el-option v-for="item in 32" :key="item" :label="item<10?'0'+item:item"
                                        :value="item<10?'0'+item:item" />
                                </el-select>
                                <span v-else>{{row.code }}</span>
                            </template>
                        </vxe-column>
                        <vxe-column field="featureId" title="传感器名称">
                            <template #default="{ row }">
                                <el-cascader ref="elCascader" v-if="row.show" v-model="row.featureId"
                                    :options="state.attainSensorNameList" :props="state.featureProps"
                                    @change="handleChange($event,row)" />
                                <span v-else>
                                    <span v-if="row.featureId">
                                        {{row.featureId.includes('D')?'开关量':row.featureId.includes('A')?'模拟量':'累积量'}}/{{row.name}}
                                    </span>
                                    <span v-else></span>
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="unit" title="单位">
                        </vxe-column>
                        <vxe-column title="操作" width="160">
                            <template #default="{ row,rowIndex }">
                                <template v-if="row.show">
                                    <el-button type="primary" @click="saveRowEvent(row)">确定</el-button>
                                </template>
                                <template v-else>
                                    <el-button type="primary" @click="editRowEvent(row)">编辑</el-button>
                                </template>
                                <el-button type="danger" @click="cancelRowEvent(row,rowIndex)">删除
                                </el-button>
                            </template>
                        </vxe-column>
                    </vxe-table>
                    <div style="text-align: center;">
                        <el-button link type="primary" @click="addStationClick">
                            <el-icon>
                                <Plus />
                            </el-icon>新增
                        </el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>
        <el-form ref="formRef" :model="state.formData" :rules="state.rules" v-if="mobanType == 'D'"
            label-position="top">
            <el-row :gutter="20" style="margin-top:10px;position: relative;" v-if="tabradio=='detail'">
                <el-col :span="16">
                    <div class="fbc">
                        <el-form-item label="模版类型" prop="templateType">
                            <el-select v-model="state.formData.templateType" style="margin-right: 10px;">
                                <el-option v-for="item in ['电源模版']" :key="item" :label="item" :value="item" />
                            </el-select>
                        </el-form-item>
                        <slot name="formtemDatatype"></slot>
                        <el-form-item label="模板名称" prop="templateName">
                            <el-input v-model="state.formData.templateName" placeholder="请输入"></el-input>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="输入口数" prop="inputPort">
                        <el-select v-model="state.formData.inputPort" placeholder="请选择" @change="inputPortChnage">
                            <el-option v-for="dict in [{
                                label:16,
                                value:16
                            },{
                                label:40,
                                value:40
                            },{
                                label:68,
                                value:68
                            }]" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8" style="position: relative;">
                    <el-form-item prop="powerTypeId">
                        <label slot="label">
                            <span style="color:#f56c6c;">*</span><span>电源类型</span>
                            <el-button link type="primary" style="margin-left:5px;" @click="helpClick">帮助
                            </el-button>
                        </label>
                        <el-select v-model="state.formData.powerTypeId" placeholder="请选择" clearable.
                            @change="powerTypeIdChange">
                            <el-option v-for="dict in state.PowerTypeList" :key="dict.id" 
                            :label="dict.powerTypeName"
                                :value="dict.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="电源号" prop="powerNo">
                        <el-select v-model="state.formData.powerNo" placeholder="请选择" clearable>
                            <el-option v-for="dict in [{
                                label:'一号电源',
                                value:1
                            },{
                                label:'二号电源',
                                value:2
                            },{
                                label:'三号电源',
                                value:3
                            }]" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <div v-if="state.attainHelpShow" style="left: 0;top: 152px;width: 100%;
                    z-index: 100;background-color: #fff;position: absolute;
                    border-radius: 8px;border: 1px solid rgba(0, 186, 173, 0.1)
                    ">
                    <div style="background-color: rgba(0, 186, 173, 0.1);padding: 6px;"><span>帮助({{state.powerTypeIdName}})</span></div>
                    <vxe-table border="inner" height="300" show-overflow ref="tablepowerRef"
                        @checkbox-change="checkchange" @checkbox-all="checkchange" :data="state.attainHelpList">
                        <vxe-column type="checkbox" :width="44"></vxe-column>
                        <vxe-column type="seq" :width="55" title="序号"></vxe-column>
                        <vxe-column field="sensorName" title="名称">
                        </vxe-column>
                        <vxe-column field="sensorType" title="传感器类型"></vxe-column>
                        <vxe-column field="rangeScale" title="量程范围"></vxe-column>
                        <vxe-column field="frequencyScale" title="频率范围"></vxe-column>
                    </vxe-table>
                    <div style="text-align: right;margin-top: 10px;">
                        <el-button type="info" @click="daoruTempcancel">取消</el-button>
                        <el-button type="primary" @click="daoruTemp">导入模板</el-button>
                    </div>
                </div>
                <el-col :span="24">
                    <vxe-table border="inner" height="500" show-overflow ref="tablepowerRef"
                        :column-config="{resizable: true}" :data="state.formData.powerTemplateList"
                        :key="state.formData.powerTemplateList">
                        <vxe-column field="id" title="测点号">
                            <template #default="{ row }">
                                <el-select v-model="row.id" placeholder="请选择" clearable>
                                    <el-option v-for="dict in state.loopBetweenNumbers" :key="dict" :label="dict"
                                        :value="dict" />
                                </el-select>
                            </template>
                        </vxe-column>
                        <vxe-column field="featureId" title="传感器名称">
                            <template #default="{ row }">
                                <el-cascader v-if="row.powerNodeDto" ref="elCascaderpower" v-model="row.featureId"
                                    :options="[row.powerNodeDto]" :props="state.featureProps"
                                    @change="handlepowerChange($event,row)" />
                            </template>
                        </vxe-column>
                        <vxe-column field="unit" title="单位"></vxe-column>
                        <!-- <vxe-column field="frequencyScale" title="频率范围"></vxe-column> -->
                        <vxe-column title="操作" width="160">
                            <template #default="{ row,rowIndex }">
                                <el-button link type="danger" @click="cancelpowerRowEvent(row,rowIndex)">删除</el-button>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </el-col>
            </el-row>
        </el-form>
        <el-form ref="formRef" :model="state.formData" :rules="state.rules" v-if="mobanType == 'A'"
            label-position="top">
            <el-row :gutter="20" style="margin-top:10px;" v-if="tabradio=='detail'">
                <el-col :span="12">
                    <div class="fbc">
                        <slot name="formtemDatatype"></slot>
                        <el-form-item label="模板名称" prop="name">
                            <el-input v-model="state.formData.name" placeholder="请输入"></el-input>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="原因" prop="reason">
                        <el-input type="textarea" v-model="state.formData.reason" placeholder="请输入">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="处理措施" prop="measure">
                        <el-input type="textarea" v-model="state.formData.measure" placeholder="请输入">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="处理结果" prop="result">
                        <el-input type="textarea" v-model="state.formData.result" placeholder="请输入">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-form ref="formRef" :model="state.formData" :rules="state.rules" v-if="mobanType == 'B'"
            label-position="top">
            <el-row :gutter="20" style="margin-top:10px;" v-if="tabradio=='detail'">
                <el-col :span="12">
                    <div class="fbc">
                        <slot name="formtemDatatype"></slot>
                        <el-form-item label="模板名称" prop="templateName">
                            <el-input v-model="state.formData.templateName" placeholder="请输入"></el-input>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="类型" prop="templateType">
                        <el-select v-model="state.formData.templateType" placeholder="请选择" clearable
                            @change="changeType">
                            <el-option v-for="dict in state.conditionList" :key="dict" :label="dict" :value="dict" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6" v-if="state.formData.templateType!='开关量'">
                    <el-form-item label="单位" prop="unit">
                        <el-input v-model="state.formData.unit" placeholder="请输入">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <h4>编辑公式</h4>
                    <el-form-item label="计算因子" prop="parentAreaId">
                        <el-cascader ref="cascaderValue" v-model="state.formData.parentAreaId" @change="nodeclick"
                            :options="state.pressionList" clearable :props="{  children: 'children',
                            value: 'code', label: 'name',emitPath:false}" />
                        <el-button style="margin-left:10px" type="primary" plain @click="selSubmitClick">选择
                        </el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-tag class="hover" style="margin-right:10px;" v-for="tag in state.dynamicTags" :key="tag.code"
                        closable @close="handleClose(tag)" @click="processbtnClick(tag.name,tag.code)">
                        {{ tag.name }}
                    </el-tag>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="运算符号" prop="stationTypeName">
                        <el-button style="padding:20px;margin:10px 5px;" v-for="item in state.biaodaList" plain
                            @click="processbtnClick(item.sub)">
                            {{ item.name }}<br />
                            {{ item.sub }}
                        </el-button>
                    </el-form-item>
                </el-col>
                <p style="font-size:14px;margin-left:10px;">公式（请点击上方计算因子与运算符号填入公式，键盘可直接录入数字与符号）</p>
                <el-col :span="24">
                    <el-form-item label="" prop="stationTypeName">
                        <div class="fbc w100">
                            <el-input style="width:98%;" id="textarea" type="textarea"
                                v-model="state.formData.expression" placeholder="请输入">
                            </el-input>
                            <span style="white-space: pre-wrap;display:inline-block
                                ;background: rgba(0, 186, 173, 1);
                                border-radius: 0px 2px, 2px, 0px;
                                color:#fff;writing-mode: vertical-rl;
                                padding:10px;
                                cursor: pointer;
                                " @click="yanzheng">验证公式</span>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-row :gutter="20" style="margin-top:10px;" v-if="mobanType == 5 || tabradio=='log'">
            <el-col :span="16">
                <el-form-item label="选择日期" label-position="left">
                    <el-date-picker v-model="state.useQueryObj.time" type="datetimerange" range-separator="-"
                        start-placeholder="请选择" end-placeholder="请选择" value-format="YYYY-MM-DD HH:mm:ss"
                        :clearable="false" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="模板类型" prop="templateType" label-position="left">
                    <el-select v-model="state.useQueryObj.templateType" style="margin-right: 10px;">
                        <el-option v-for="item in ['分站模板','电源模板','分析模板','公式']" :key="item" :label="item"
                            :value="item" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="模板名称" prop="templateName" label-position="left">
                    <el-input v-model="state.useQueryObj.templateName" placeholder="请输入"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <vxe-table border="inner" height="500" show-overflow ref="tableRef" :data="state.tableData">
                    <vxe-column type="seq" title="序号" width="50"></vxe-column>
                    <vxe-column v-for="(item, index) in state.tableheads" :field="item.field" :title="item.title"
                        :width="item.width ? item.width : ''" :key="index">
                    </vxe-column>
                </vxe-table>
            </el-col>
            <el-col :span="24" >
                <el-pagination style="float: right;margin: 0 20px;" v-model:current-page="state.useQueryObj.pageNum"
                    v-model:page-size="state.useQueryObj.pageSize" :page-sizes="[10, 20, 30, 40]" background
                    layout="total, sizes, prev, pager, next, jumper" :total="state.useQueryObj.total"
                    @size-change="pagechangeSize" @current-change="pagechange" />
            </el-col>
        </el-row>
        <div v-if="tabradio!='log'&& mobanType != 5" class="footer-form" style="text-align:right;display:flex;
        justify-content: space-between;">
            <span>
                <el-button v-if="mobanType == 'D'&&!editId" type="danger" @click="powerReset">重置</el-button>
                <el-button type="danger" @click="delTemp" v-if="editId">删除</el-button>
            </span>
            <span>
                <slot name="curdBtnList">
                </slot>
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="submitForm">
                    确定
                </el-button>
            </span>
        </div>
        <!-- 删除提示 -->
        <el-dialog v-model="state.delTip" width="260px">
            <div class="del_box">
                <img src="@/assets/images/删除模板.png" alt="" />
                <div class="fonts">
                    <div class="one">是否删除当前模板？</div>
                    <div class="two">删除后不可恢复！</div>
                </div>
                <div>
                    <el-button style="width: 72px; margin: 0 20px 0 0" @click="state.delTip = false">取消</el-button>
                    <el-button style="width: 72px" type="danger" @click="confirmDel">删除</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script setup>
    import {
        onBeforeMount,
        ref,
        watch,
        reactive,
        toRefs,
        toRef,
        watchEffect,
        nextTick
    } from "vue"
    import axios from "@/utils/request"
    import {
        ElMessage
    } from "element-plus";
    import {
        searchgetPowerTypeList,
    } from "@/api/config";
    const {
        proxy
    } = getCurrentInstance();
    import _ from 'lodash'
    import dayjs from "dayjs";
    import {
        table_headers
    } from "@/components/commonCom/table_headers";
    const props = defineProps({
        mobanType: {
            default: 'C',
            type: String
        },
        tabradio: {
            default: 'detail',
            type: String
        },
        editId: {
            default: undefined,
            type: String
        },
        isShow: {
            default: undefined,
            type: String
        },
        editWatchState: {
            default: false,
            type: Boolean
        },
        mobanTypeObj: {
            default: undefined,
            type: Object
        },
        mobanTypeObjoverview: {
            default: undefined,
            type: Object
        }
    })
    const emits = defineEmits(["addModal", 'delTemp'])
    const tableRef = ref()
    const state = reactive({
        loopBetweenNumbers: [],
        tableheads: computed(() => table_headers.templateUsageLog),
        useQueryObj: {
            pageNum: 1,
            pageSize: 10,
            total: 0,
            time: [dayjs().subtract(1, 'month').format('YYYY-MM-DD HH:mm:ss'), dayjs().format(
                'YYYY-MM-DD HH:mm:ss')]
        },
        powerTemplateList: [],
        delTip: false,
        delId: 0,
        stationEditShow: false,
        formData: {
            nodeList: []
        },
        nodeList: [],
        rules: {
            templateType: [{
                required: true,
                message: "请选择模板类型",
                trigger: "change",
            }],
            templateName: [{
                required: true,
                message: "请选择模板名称",
                trigger: "blur",
            }],
            inputPort: [{
                required: true,
                message: "请选择输入口数",
                trigger: "blur",
            }],
            powerTypeId: [{
                required: true,
                message: "请选择电源类型",
                trigger: "blur",
            }],
            powerNo: [{
                required: true,
                message: "请选择电源号",
                trigger: "blur",
            }],
        },
        tableData: [],
        mobanList: [],
        conditionList: ['模拟量', '开关量'],
        tagValue: undefined,
        tagCode: undefined,
        dynamicTags: [],
        biaodaList: [{
                name: '加',
                sub: '+'
            }, {
                name: '减',
                sub: '-'
            }, {
                name: '乘',
                sub: '*'
            }, {
                name: '除',
                sub: '/'
            }, {
                name: '左括号',
                sub: '('
            }, {
                name: '右括号',
                sub: ')'
            }, {
                name: '与',
                sub: '&&'
            }, {
                name: '或',
                sub: '||'
            }, {
                name: '等于',
                sub: '=='
            }, {
                name: '大于',
                sub: '>'
            }, {
                name: '大于等于',
                sub: '>='
            },
            {
                name: '小于',
                sub: '<'
            }, {
                name: '小于等于',
                sub: '<='
            }, {
                name: '清',
                sub: '空'
            }
        ],
        pressionList: [],
        editId: undefined,
        attainSensorNameList: [],
        featureProps: {
            children: 'children',
            value: "featureId",
            label: "commonField",
            emitPath: false,
        },
        PowerTypeList: [],
        attainHelpList: [],
        attainHelpShow: false,
        powerTypeIdName: undefined,
        pageChange: false

    })

    function getTreeName(data, target, result) {

        for (let item of data) {
            if (item.featureId === target) {
                //将查找到的目标数据加入结果数组中
                //可根据需求unshift(item.id)或unshift(item)
                result.unshift(item.commonField)
                return result.join('/')
            }
            if (item.children && item.children.length > 0) {
                //根据查找到的结果往上找父级节点
                let isFind = getTreeName(item.children, target, result)
                if (isFind) {
                    result.unshift(item.commonField)
                    return result.join('/')
                }
            }
        }
        console.log(result, "resultresult")
        //走到这说明没找到目标
        return []
    }

    // 获取计算因子下拉
    function searchexpressionListdata() {
        axios.get('template/expression/getExpressionTree').then(res => {
            state.pressionList = res.data
        })
    }
    searchexpressionListdata()
    // 公式类型事件
    const changeType = (val) => {
        if (val == '模拟量') {
            state.formData.unit = 'ppm'
        } else {
            state.formData.unit = ''
        }
    }
    // 计算因子
    function nodeclick(val) {
        if (val) {
            state.tagValue = proxy.$refs["cascaderValue"].getCheckedNodes()[0].label
            state.tagCode = val
        } else {

        }
    }

    function selSubmitClick() {
        if (state.formData.parentAreaId) {
            state.dynamicTags.push({
                name: state.tagValue,
                code: state.tagCode
            })
            state.dynamicTags = Array.from(new Set(state.dynamicTags))
        } else {
            ElMessage.warning('请选择计算因子')
        }
    }

    function handleClose(tag) {
        state.dynamicTags = _.pullAllWith(state.dynamicTags, [tag], _.isEqual);
    }

    function processbtnClick(myValue, type) {
        if (type) {
            if (!state.formData.nameDtoList) {
                state.formData.nameDtoList = []
            }
            state.formData.nameDtoList.push({
                name: myValue,
                code: type
            })
        }
        if (myValue != '空') {
            const myField = document.querySelector('#textarea')
            var startPos = myField.selectionStart
            var endPos = myField.selectionEnd
            state.formData.expression = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos,
                myField.value
                .length)
            nextTick(() => {
                myField.focus()
                myField.setSelectionRange(endPos + myValue.length, endPos + myValue.length)
            })
        } else {
            state.formData.expression = ''
        }
    }

    function yanzheng() {
        axios.post('/template/expression/check', {
            expression: state.formData.expression,
            templateType: state.formData.templateType,
            nameDtoList: state.formData.nameDtoList
        }).then(res => {
            if (res.code == 200) {
                ElMessage.success(res.data)
            }

        })
    }
    // 获取公式详情
    const getExpressionInfo = async (id) => {
        await axios.get(`template/expression/getExpressionById/${id}`).then(res => {
            state.formData = res.data
            state.dynamicTags = []
            res.data.nameDtoList.forEach(it => {
                state.dynamicTags.push({
                    name: it.name,
                    code: it.code
                })
                state.dynamicTags = _.uniqBy(state.dynamicTags, 'code');
                state.pressionList.forEach(item => {
                    item.children.forEach(item2 => {
                        if (item2.children) {
                            item2.children.forEach(item3 => {
                                if (it.code == item3.code) {
                                    item3.disabled = true
                                }
                            })
                        } else {
                            if (it.code == item2.code) {
                                item2.disabled = true
                            }
                        }
                    })
                })
            })
        })
    }
    // 获取分析详情
    const getaysInfo = async (id) => {
        await axios.post('template/analysis/list', {
            id: id
        }).then(res => {
            state.formData = res.data[0]
        })
    }
    // 获取分析详情
    const gestationInfo = async (id) => {
        await axios.post('templateStation/getById', {
            id: id
        }).then(res => {
            state.formData = res.data
            state.nodeList = res.data.nodeList
        })
    }
    // 获取电源详情
    const gespowerInfo = async (id) => {
        await axios.post('/templatePower/getById', {
            id: id
        }).then(res => {
            state.formData = res.data
            state.formData.powerTemplateList.forEach(async item => {
                item.powerNodeDto = await getpowerTemplateList(item.featureId.includes(
                    'A') ? 'A' : 'D')
                item.name = getTreeName([item.powerNodeDto], item.featureId, [])
            })
            if (res.data.inputPort == 16) {
                loopBetweenNumbers(1, 16)
            } else if (res.data.inputPort == 40) {
                loopBetweenNumbers(17, 40)
            } else if (res.data.inputPort == 68) {
                loopBetweenNumbers(33, 68)
            }

        })
    }
    /**
     * 分站模块操作
     */
    // 新增分站模块
    function addStationClick() {
        if (!state.nodeList) {
            state.nodeList = []
        }
        state.nodeList.push({
            show: true
        })
        state.formData.nodeList = state.nodeList
    }
    const editRowEvent = (row) => {
        row.show = !row.show
    }
    const saveRowEvent = (row) => {
        row.show = !row.show
    }
    const cancelRowEvent = (row, index) => {
        state.formData.nodeList.splice(index, 1);
        const $table = tableRef.value
        if ($table) {
            $table.remove(row)
        }
    }

    function powerReset() {
        state.formData = {}
    }
    const cancelpowerRowEvent = (row, index) => {
        state.formData.powerTemplateList.splice(index, 1);
        const $table = proxy.$refs['tablepowerRef']
        if ($table) {
            $table.remove(row)
        }
    }
    const handlepowerChange = (value, row) => {
        row.name = getTreeName([row.powerNodeDto], row.featureId, [])
    }
    const handleChange = (value, row) => {
        if (proxy.$refs['elCascader'].cascaderPanelRef
            .getCheckedNodes()) {
            row.name = proxy.$refs['elCascader'].cascaderPanelRef
                .getCheckedNodes()[0].label
            row.unit = proxy.$refs['elCascader'].cascaderPanelRef
                .getCheckedNodes()[0].data.unit
        }
    }
    // 获取树形接口
    function gettemplateStation() {
        axios.get('/templateStation/attainSensorNameList').then(res => {
            state.attainSensorNameList = res.data
        })
    }
    // 获取电源类型数据
    function getsearchgetPowerTypeList() {
        state.loopBetweenNumbers=loopBetweenNumbers(33, 68)
        searchgetPowerTypeList().then((res) => {
            state.PowerTypeList = res.data;
        });
    }
    getsearchgetPowerTypeList()
    gettemplateStation()
    // 获取电源模板列表
    function getpowerTemplateList(type) {
        return new Promise((resolve, reject) => {
            axios.post('/templatePower/attainPowerTemplate', {
                type: type
            }).then(res => {
                resolve(res.data)
            })
        })
    }

    function attainHelppost() {
        let data = {
            "powerTypeId": state.formData.powerTypeId,
            "powerNo": state.formData.powerNo,
        }
        if ((state.formData.powerTypeId ||state.formData.powerTypeId==0) && state.formData.powerNo) {
            axios.post('power/supply/attainHelp', data).then(res => {
                state.attainHelpShow = true
                state.attainHelpList = res.data
            })
        } else {
            proxy.$modal.msgWarning('请选择电源类型与电源号！');
        }
    }

    function daoruTempcancel() {
        state.attainHelpShow = false
    }

    function daoruTemp() {
        if (state.formData.powerTemplateList.length > 0) {
            state.attainHelpShow = false
        } else {
            proxy.$modal.msgWarning('请选择需要导入模板的数据！');
        }
    }

    function loopBetweenNumbers(start, end) {
        // 确保 start 小于 end
        if (start > end) {
            [start, end] = [end, start]; // 交换值
        }

        for (let i = start; i <= end; i++) {
            state.loopBetweenNumbers.push(i)
        }
    }
    // 获取输入口数据
    function inputPortChnage(val) {
        state.loopBetweenNumbers = []
        if (val == 16) {
            loopBetweenNumbers(1, 16)
        } else if (val == 40) {
            loopBetweenNumbers(17, 40)
        } else if (val == 68) {
            loopBetweenNumbers(33, 68)
        }
    }

    function helpClick() {
         state.PowerTypeList.forEach(item => {
            if (item.id == state.formData.powerTypeId) {
                state.powerTypeIdName = item.powerTypeName
            }
        })
        attainHelppost()
    }
    async function checkchange(e) {
        e.records.forEach(async item => {
            item.powerNodeDto = await getpowerTemplateList(item.type)
            item.name = getTreeName([item.powerNodeDto], item.featureId, [])
        })
        state.formData.powerTemplateList = e.records
    }

    function powerTypeIdChange(val) {
        state.PowerTypeList.forEach(item => {
            if (item.id == val) {
                state.powerTypeIdName = item.powerTypeName
            }
        })
    }

    function getlogList() {
        // delete state.useQueryObj.total
        axios.post('/templateUsageLog/list', state.useQueryObj).then(res => {
            state.tableData = res.data.list
            state.useQueryObj.total = res.data.total
        })
    }
    // 日志查询
    function handleQuery() {
        if (state.useQueryObj.time && state.useQueryObj.time.length > 0) {
            state.useQueryObj.startTime = dayjs(state.useQueryObj.time[0]).format('YYYY-MM-DD HH:mm:ss')
            state.useQueryObj.endTime = dayjs(state.useQueryObj.time[1]).format('YYYY-MM-DD HH:mm:ss')
        }
        getlogList()
    }

    function resetQuery() {
        state.useQueryObj.pageNum = 1
        state.useQueryObj.pageSize = 10
        state.useQueryObj.templateName = undefined
        state.useQueryObj.templateType = undefined
        state.useQueryObj.startTime = undefined
        state.useQueryObj.endTime = undefined
        state.useQueryObj.time = [dayjs().subtract(1, 'month').format('YYYY-MM-DD HH:mm:ss'), dayjs().format(
            'YYYY-MM-DD HH:mm:ss')]
       if (state.useQueryObj.time && state.useQueryObj.time.length > 0) {
            state.useQueryObj.startTime = dayjs(state.useQueryObj.time[0]).format('YYYY-MM-DD HH:mm:ss')
            state.useQueryObj.endTime = dayjs(state.useQueryObj.time[1]).format('YYYY-MM-DD HH:mm:ss')
        }
        getlogList()
    }
    // 分页
    function pagechange(val) {
        state.useQueryObj.pageNum = val
        state.pageChange = true
        getlogList()
    }
    // 分页
    function pagechangeSize(val) {
        state.useQueryObj.pageNum = 1
        state.useQueryObj.pageSize = val
        state.pageChange = true
        getlogList()

    }
    watch(() => props.mobanType, (newValue) => {
         if (state.useQueryObj.time && state.useQueryObj.time.length > 0) {
            state.useQueryObj.startTime = dayjs(state.useQueryObj.time[0]).format('YYYY-MM-DD HH:mm:ss')
            state.useQueryObj.endTime = dayjs(state.useQueryObj.time[1]).format('YYYY-MM-DD HH:mm:ss')
        }
        state.nodeList = [{
            show: true
        }]
        state.formData.nodeList = [{
            show: true
        }]
        if (newValue == 'B') {
            state.useQueryObj.templateType = '公式'
            if (!state.pageChange) {
                getlogList()
            }
        } else if (newValue == 'A') {
            state.useQueryObj.templateType = '分析模板'
            if (!state.pageChange) {
                getlogList()
            }
        } else if (newValue == 'C') {
            state.useQueryObj.templateType = '分站模板'
            if (!state.pageChange) {
                getlogList()
            }
        } else if (newValue == 'D') {
            state.useQueryObj.templateType = '电源模板'
            if (!state.pageChange) {
                getlogList()
            }
        } else if (newValue == 5) {
            state.useQueryObj.templateType = undefined
            if (!state.pageChange) {
                getlogList()
            }
        }
    }, {
        immediate: true
    });
    watchEffect(() => {
        state.attainHelpShow = false
        state.editId = props.editId
        if(!props.isShow){
            if (props.editId) {
                if (props.mobanType == 'B') {
                    getExpressionInfo(props.editId);
                } else if (props.mobanType == 'A') {
                    getaysInfo(props.editId)
                } else if (props.mobanType == 'C') {
                    gestationInfo(props.editId)
                } else if (props.mobanType == 'D') {
                    state.loopBetweenNumbers = []
                    gespowerInfo(props.editId)
                }
                if (props.mobanTypeObj) {
                    state.nodeList = props.mobanTypeObj.nodeList
                    state.formData = props.mobanTypeObj
                }
            } else {
                if (props.mobanTypeObjoverview) {
                        state.nodeList = props.mobanTypeObjoverview.nodeList
                        state.formData = props.mobanTypeObjoverview
                } 
            }
        }else{
            {
                state.formData = {}
                state.nodeList = [{
                    show: true
                }]
                state.formData.nodeList = state.nodeList
                state.dynamicTags = []
                state.formData.parentAreaId = undefined
                state.dynamicTags = []
            }
            if (props.mobanType == 'D') {
                getpowerTemplateList()
                // state.formData.inputPort = 68
                // loopBetweenNumbers(41, 68)
            }
        }
        // } else {
        //     console.log("新增不存在")
        //     state.formData.nodeList = [{
        //         show: true
        //     }]
        //     state.dynamicTags = []
        //     state.formData.parentAreaId = undefined
        //     state.dynamicTags = []

        // }

    })

    function submitForm() {
        proxy.$refs["formRef"].validate(valid => {
            if (valid) {
                let url = ''
                if (props.editId) {
                    if (props.mobanType == 'A') {
                        url = '/template/analysis/update'
                    } else if (props.mobanType == 'B') {
                        url = '/template/expression/saveTemplate'
                    } else if (props.mobanType == 'C') {
                        url = '/templateStation/modifyTemplateStation'
                    } else if (props.mobanType == 'D') {
                        delete state.formData.nodeList
                        url = '/templatePower/modifyTemplatePower'
                    }
                } else {
                    if (props.mobanType == 'A') {
                        url = '/template/analysis/save'
                    } else if (props.mobanType == 'B') {
                        url = '/template/expression/saveTemplate'
                    } else if (props.mobanType == 'C') {
                        url = '/templateStation/addTemplateStation'
                    } else if (props.mobanType == 'D') {
                        delete state.formData.nodeList
                        url = '/templatePower/addTemplatePower'
                    }
                }
                axios.post(url, state.formData).then(res => {
                    if (res.code == 200) {
                        proxy.$modal.msgSuccess(res.msg);
                        emits("addModal", false)
                    }
                })
            }
        })
    }

    function cancel() {
        emits("addModal", 1)
    }
    // 删除模板
    function delTemp() {
        emits("delTemp", state.formData.id)
        state.delTip = true;
        state.delId = state.formData.id;
    }
    // 确认删除
    const confirmDel = () => {
        if (props.mobanType == "A") {
            axios
                .post("/template/analysis/delete", {
                    id: state.delId,
                })
                .then((res) => {
                    if (res.code == 200) {
                        state.delTip = false;
                        emits("addModal", 2)
                        proxy.$modal.msgSuccess(res.msg);
                    }
                });
        } else if (props.mobanType == "B") {
            axios
                .post(`/template/expression/deleteExpressionById/${state.delId}`)
                .then((res) => {
                    if (res.code == 200) {
                        emits("addModal", 2)
                        state.delTip = false;
                        proxy.$modal.msgSuccess(res.msg);
                    }
                });
        } else if (props.mobanType == "C") {
            axios
                .post(`/templateStation/del`, [state.delId])
                .then((res) => {
                    if (res.code == 200) {
                        emits("addModal", 2)
                        state.delTip = false;
                        proxy.$modal.msgSuccess(res.msg);
                    }
                });
        } else if (props.mobanType == "D") {
            axios
                .post(`/templatePower/del`, [state.delId])
                .then((res) => {
                    if (res.code == 200) {
                        emits("addModal", 2)
                        state.delTip = false;
                        proxy.$modal.msgSuccess(res.msg);
                    }
                });
        }
    };
</script>
<style lang="scss" scoped>
    .footer-form {
        margin-top: 40px;
        text-align: right;
        position: sticky;
        z-index: 13;
        bottom: 10px;
    }

    .del_box {
        padding: 0 20px;
        height: 235px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;

        img {
            width: 100px;
        }

        .fonts {
            color: rgba(62, 70, 79, 1);
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;

            .one {
                font-size: 16px;
                font-weight: 700;
            }

            .two {
                font-size: 14px;
                font-weight: 400;
            }
        }
    }
</style>